package com.threadtest;

import java.util.concurrent.TimeUnit;

/**
 * @program: springbootRabbitmq->ThreadTest
 * @description: 同步异步测试
 * @author: G_Y
 * @create: 2019-08-13 19:29
 **/
public class ThreadTest {
    public static void main(String[] args) {
        Person person = Person.getInstance();
        new Thread(new T1(person)).start();
        new Thread(new T2(person)).start();
        new Thread(new T3()).start();
    }
}
class Person {
    private static Person person = new Person();
    private Person(){}
    public static Person getInstance(){
        return person;
    }
    public synchronized void say() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            TimeUnit.MILLISECONDS.sleep(2);
            System.out.println("say" + i);
        }
    }
    public synchronized void hello() {
        for (int i = 0; i < 10; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("hello" + i);
        }
    }
    public static void go() {
        synchronized (person){
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("go" + i);
            }
        }
    }
}
class T1 implements Runnable {
    Person p;
    public T1(Person p) {
        this.p = p;
    }
    @Override
    public void run() {
        p.hello();
    }
}
class T2 implements Runnable {
    Person p;
    public T2(Person p) {
        this.p = p;
    }
    @Override
    public void run() {
        try {
            p.say();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class T3 implements Runnable {
    @Override
    public void run() {
        Person.go();
    }
}